
//action
document.addEventListener('DOMContentLoaded', function() {

    // 循环遍历单选按钮并为其添加事件监听器
    document.querySelectorAll('input[type="radio"][name="mode"]').forEach(function(radioButton) {
        radioButton.addEventListener('change', function() {
            // 当选项发生变化时，获取当前选中项的值
            var selectedValue = document.querySelector('input[type="radio"][name="mode"]:checked').value;
            console.debug("当前选中项的值为：" + selectedValue);
        });
    });

	//连接按钮
	document.getElementById("set_button").addEventListener('click', function() {
		mode = document.querySelector('input[name="mode"]:checked').value;
		selectProxy(mode,null);
		console.debug("mode=",mode);
		saveProxySetting(null);
	});

	//保存按钮
	document.getElementById("save_button").addEventListener('click', function() {
		saveProxySetting(null);
	});

	//重置按钮
	document.getElementById("reset_button").addEventListener('click', function() {
		pac_url = "";
		mode = "";
		singleProxySetting = null;
		proxyForHttpSetting = null;
		proxyForHttpsSetting = null;
		proxyForFtpSetting = null;
		fallbackProxySetting = null;
		bypass_list = null;
		advanced_settings_checkbox = null;
		chrome.storage.local.set({ "pac_url": pac_url }).then(() => {
			console.debug("pac_url is set, value: " + pac_url);
		});
		chrome.storage.local.set({ "mode": mode }).then(() => {
			console.debug("mode is set, value: " + mode);
		});
		chrome.storage.local.set({ "singleProxySetting": singleProxySetting }).then(() => {
			console.debug("singleProxySetting is set, value: " + singleProxySetting);
		});
		chrome.storage.local.set({ "proxyForHttpSetting": proxyForHttpSetting }).then(() => {
			console.debug("singleProxySetting is set, value: " + proxyForHttpSetting);
		});
		chrome.storage.local.set({ "proxyForHttpsSetting": proxyForHttpsSetting }).then(() => {
			console.debug("proxyForHttpsSetting is set, value: " + proxyForHttpsSetting);
		});
		chrome.storage.local.set({ "proxyForFtpSetting": proxyForFtpSetting }).then(() => {
			console.debug("proxyForFtpSetting is set, value: " + proxyForFtpSetting);
		});
		chrome.storage.local.set({ "fallbackProxySetting": fallbackProxySetting }).then(() => {
			console.debug("fallbackProxySetting is set, value: " + fallbackProxySetting);
		});
		chrome.storage.local.set({ "bypass_list": bypass_list }).then(() => {
			console.debug("bypass_list is set, value: " + bypass_list);
		});
		chrome.storage.local.set({ "advanced_settings_checkbox": advanced_settings_checkbox }).then(() => {
			console.debug("advanced_settings_checkbox is set, value: " + advanced_settings_checkbox);
		});
		useSystemProxy(true,null);
		// 刷新当前文档
		location.reload();

	});



	//高级设置的显示变化
	document.getElementById("advanced_settings_checkbox").addEventListener('change', function() {
		if (this.checked) {
			var advancedSettingsElements = document.querySelectorAll('[name="advanced_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'block';
			});

			var advancedSettingsElements = document.querySelectorAll('[name="simple_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'none';
			});
		} else if (!this.checked) {
			var advancedSettingsElements = document.querySelectorAll('[name="advanced_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'none';
			});
			var advancedSettingsElements = document.querySelectorAll('[name="simple_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'block';
			});
		}
	});

	//读取保存的设置
	echoProxySetting(null);
	

});


//variable init
var pac_url = "";
var mode = "";
var singleProxySetting = {};
var proxyForHttpSetting = {};
var proxyForHttpsSetting = {};
var proxyForFtpSetting = {};
var fallbackProxySetting = {};
var bypass_list = [];
var advanced_settings_checkbox = null;
// function
//选择代理
function selectProxy(proxyMode,callback){
    switch (proxyMode) {
		case "direct":
			noProxy(true,callback);
		break;
		case "auto_detect":
			autoDetectProxy(true,callback);
		break;
		case "pac_script":
			pac_url = document.getElementById("pac_url").value;
			pacScriptProxy(true,pac_url,callback);
		break;
		case "fixed_servers":
			if (document.getElementById("advanced_settings_checkbox").checked) {
				getAdvancedProxySetting(true,callback);
			} else {
				getSimpleProxySetting(true,callback);
			}
		break;
		case "system":
			useSystemProxy(true,callback);
			break;
		default:
			noProxy(true,callback);
		break;
	}
	
}

//保存设置
function saveProxySetting(callback){
	console.debug("function saveProxySetting start");
	//保存mode
	mode = document.querySelector('input[name="mode"]:checked').value;
	chrome.storage.local.set({ "mode": mode }).then(() => {
	    console.debug("mode is set, value: " + mode);
	});
	//保存是否开启高级选项
	advanced_settings_checkbox = document.getElementById("advanced_settings_checkbox").checked;
	chrome.storage.local.set({ "advanced_settings_checkbox": advanced_settings_checkbox }).then(() => {
	    console.debug("advanced_settings_checkbox is set, value: " + advanced_settings_checkbox);
	});

	//保存pac_url
	pac_url = document.getElementById("pac_url").value;
	chrome.storage.local.set({ "pac_url": pac_url }).then(() => {
		console.debug("pac_url is set, value: " + pac_url);
	});
	//保存singleProxySetting
	var proxy_host = document.getElementById("server_address").value;
	var proxy_port = Number(document.getElementById("server_port").value);
	var server_protocol = document.getElementById("server_protocol").value;
	singleProxySetting = {
	    scheme:server_protocol,
		host:proxy_host,
		port:proxy_port
	};
	chrome.storage.local.set({ "singleProxySetting": singleProxySetting }).then(() => {
		console.debug("singleProxySetting is set, value: " + singleProxySetting);
	});

	//保存高级设置
	//保存http设置
    var http_proxy_address = document.getElementById("http_proxy_address").value;
	var http_port = Number(document.getElementById("http_port").value);
	var http_server_protocol = document.getElementById("http_server_protocol").value;
	proxyForHttpSetting = {
	    scheme:http_server_protocol,
		host:http_proxy_address,
		port:http_port
	};
	chrome.storage.local.set({ "proxyForHttpSetting": proxyForHttpSetting }).then(() => {
		console.debug("singleProxySetting is set, value: " + proxyForHttpSetting);
	});

	//保存https设置
	var https_proxy_address = document.getElementById("https_proxy_address").value;
	var https_port = Number(document.getElementById("https_port").value);
	var https_server_protocol = document.getElementById("https_server_protocol").value;
	proxyForHttpsSetting = {
	    scheme:https_server_protocol,
		host:https_proxy_address,
		port:https_port
	};
	chrome.storage.local.set({ "proxyForHttpsSetting": proxyForHttpsSetting }).then(() => {
		console.debug("proxyForHttpsSetting is set, value: " + proxyForHttpsSetting);
	});

	//保存FTP设置
	var ftp_proxy_address = document.getElementById("ftp_proxy_address").value;
	var ftp_port = Number(document.getElementById("ftp_port").value);
	var ftp_server_protocol = document.getElementById("ftp_server_protocol").value;
	proxyForFtpSetting = {
	    scheme:ftp_server_protocol,
		host:ftp_proxy_address,
		port:ftp_port
	};
	chrome.storage.local.set({ "proxyForFtpSetting": proxyForFtpSetting }).then(() => {
		console.debug("proxyForFtpSetting is set, value: " + proxyForFtpSetting);
	});

	//保存fallback设置
	var fallback_proxy_address = document.getElementById("fallback_proxy_address").value;
	var fallback_port = Number(document.getElementById("fallback_port").value);
	var fallback_server_protocol = document.getElementById("fallback_server_protocol").value;
	fallbackProxySetting = {
	    scheme:fallback_server_protocol,
		host:fallback_proxy_address,
		port:fallback_port
	};
	chrome.storage.local.set({ "fallbackProxySetting": fallbackProxySetting }).then(() => {
		console.debug("fallbackProxySetting is set, value: " + fallbackProxySetting);
	});

	//保存绕行列表
	bypass_list = getBypassList(callback);
	chrome.storage.local.set({ "bypass_list": bypass_list }).then(() => {
		console.debug("bypass_list is set, value: " + bypass_list);
	});
	
	console.debug("function saveProxySetting end");
}

//读取保存的设置
async function getProxySetting(callback){
    console.debug("function getProxySetting start");
	await chrome.storage.local.get(["advanced_settings_checkbox","mode","pac_url","singleProxySetting","proxyForHttpSetting","proxyForHttpsSetting","proxyForFtpSetting","fallbackProxySetting","bypass_list"]).then((result)=>{
		console.debug("getProxySetting result=",result);
		advanced_settings_checkbox = result.advanced_settings_checkbox;
		console.debug("advanced_settings_checkbox =",result.advanced_settings_checkbox);
		mode = result.mode;
		console.debug("mode=",result.mode);
		pac_url = result.pac_url;
		console.debug("pac_url =",result.pac_url);
		singleProxySetting = result.singleProxySetting;
		console.debug("singleProxySetting =",result.singleProxySetting);
		proxyForHttpSetting = result.proxyForHttpSetting;
		console.debug("proxyForHttpSetting =",result.proxyForHttpSetting);
		proxyForHttpsSetting = result.proxyForHttpsSetting;
		console.debug("proxyForHttpsSetting =",result.proxyForHttpsSetting);
		proxyForFtpSetting = result.proxyForFtpSetting;
		console.debug("proxyForFtpSetting =",result.proxyForFtpSetting);
		fallbackProxySetting = result.fallbackProxySetting;
		console.debug("fallbackProxySetting =",result.fallbackProxySetting);
		bypass_list = result.bypass_list;
		console.debug("bypass_list=",result.bypass_list);
	});
	console.debug("function getProxySetting end");
}

//将保存的设置回显到面板
async function echoProxySetting(callback){
	console.debug("function echoProxySetting start");
	await getProxySetting(null);
	if (mode != null && mode != undefined && mode != "") {
		document.querySelector('input[name="mode"][value="' + mode + '"]').checked = true;

	}
	if (advanced_settings_checkbox != null && advanced_settings_checkbox != undefined) {
		document.getElementById("advanced_settings_checkbox").checked = advanced_settings_checkbox;
		if (advanced_settings_checkbox) {
			var advancedSettingsElements = document.querySelectorAll('[name="advanced_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'block';
			});
			var advancedSettingsElements = document.querySelectorAll('[name="simple_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'none';
			});
		} else if (!this.checked) {
			var advancedSettingsElements = document.querySelectorAll('[name="advanced_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'none';
			});
			var advancedSettingsElements = document.querySelectorAll('[name="simple_settings"]');
			advancedSettingsElements.forEach(function(element) {
				element.style.display = 'block';
			});
		}
	}

	if (pac_url!=null && pac_url!=undefined && pac_url!="") {
	    document.getElementById("pac_url").value = pac_url;
	}
	if (singleProxySetting!=null && singleProxySetting!=undefined) {
	    document.getElementById("server_address").value = singleProxySetting.host;
		document.getElementById("server_port").value = singleProxySetting.port;
		document.getElementById("server_protocol").value = singleProxySetting.scheme;
	}
	if (proxyForHttpSetting!=null && proxyForHttpSetting!=undefined) {
	    document.getElementById("http_proxy_address").value = proxyForHttpSetting.host;
		document.getElementById("http_port").value = proxyForHttpSetting.port;
	}
	if (proxyForHttpsSetting!=null && proxyForHttpsSetting!=undefined) {
	    document.getElementById("https_proxy_address").value = proxyForHttpsSetting.host;
		document.getElementById("https_port").value = proxyForHttpsSetting.port;
	}
	if (proxyForFtpSetting!=null && proxyForFtpSetting!=undefined) {
	    document.getElementById("ftp_proxy_address").value = proxyForFtpSetting.host;
		document.getElementById("ftp_port").value = proxyForFtpSetting.port;
	}
	if (fallbackProxySetting!=null && fallbackProxySetting!=undefined) {
	    document.getElementById("fallback_proxy_address").value = fallbackProxySetting.host;
		document.getElementById("fallback_port").value = fallbackProxySetting.port;
	}
	if (bypass_list!=null && bypass_list!=undefined) {
	    var bypass_str = bypass_list.join(",");
		document.getElementById("bypass_list").value = bypass_str;
	}
	console.debug("function echoProxySetting end");
}

// 设置代理
function setProxy(object,callback){
	console.debug("function setProxy start");
	console.debug("object=",object);
	//设置代理
	chrome.proxy.settings.set(object, function (){
			if (callback!=null||callback!=undefined) {
				callback(object);
			}
			//return result
			return object;
	});
	console.debug("function setProxy end");
}

//使用系统代理
function useSystemProxy(isEnable,callback){
	console.debug("function useSystemProxy start");
	var proxySetting = {
		value: {mode: "system"},
		scope: 'regular'
	}
	if (isEnable) {
		setProxy(proxySetting,callback);
	}
	console.debug("function useSystemProxy end");
}

//直连模式
function noProxy(isEnable,callback){
	console.debug("function noProxy start");
	var proxySetting = {
		value: {mode: "direct"},
		scope: 'regular'
	}
	if (isEnable) {
		setProxy(proxySetting,callback);
	}
	console.debug("function noProxy end");
}

//自动感知代理
function autoDetectProxy(isEnable,callback){
	console.debug("function autoDetectProxy start");
	var proxySetting = {
		value: {mode: "auto_detect"},
		scope: 'regular'
	}
	if (isEnable) {
		setProxy(proxySetting,callback);
	}
	console.debug("function autoDetectProxy end");
}

//代理自动配置文件
function pacScriptProxy(isEnable,scriptPath,callback){
	console.debug("function pacScriptProxy start");
	var proxySetting = {
		value: {
			mode: "pac_script",
			pacScript: {
				data: scriptPath,
				mandatory:false
			}
		},
		scope: 'regular'
	}
	if (isEnable) {
	    setProxy(proxySetting,callback);
	}
	console.debug("function pacScriptProxy end");
}

//手动设置代理
function fixedServersProxy(isEnable,rules,callback){
	console.debug("function fixedServersProxy start");
	var proxySetting = {
		value: {
			mode: "fixed_servers",
			rules: rules
		},
		scope: 'regular'
	}
	if (isEnable) {
		setProxy(proxySetting,callback);
	}
	console.debug("function fixedServersProxy end");
}

// 获取绕行列表
function getBypassList(callback){
	console.debug("function getBypassList start");
    var bypass_str = document.getElementById("bypass_list").value;
	bypass_list = splitStringByDelimiter(bypass_str);
	if(callback){
		callback(bypass_list);
	}
	console.debug("function getBypassList end");
	return bypass_list;

}

//解析绕行列表字符串
function splitStringByDelimiter(inputString) {
	console.debug("function splitStringByDelimiter start");
    // 定义正则表达式，匹配中文分号、中文逗号、英文分号、英文逗号、单个空格、多个空格
    var delimiterRegex = /[,;，；\s]+/;
    // 使用split方法将字符串分割成数组
    var segments = inputString.split(delimiterRegex);
    // 返回结果数组
	console.debug("function splitStringByDelimiter end");
    return segments;
}

//获取简易设置
function getSimpleProxySetting(isEnable,callback){
	console.debug("function getSimpleProxySetting start");
	bypass_list = getBypassList(callback);
	var proxy_host = document.getElementById("server_address").value;
	var proxy_port = Number(document.getElementById("server_port").value);
	var server_protocol = document.getElementById("server_protocol").value;
	var simpleProxyRules = {
		singleProxy:{scheme:server_protocol,host:proxy_host,port:proxy_port},
		bypassList: bypass_list
	}
	fixedServersProxy(isEnable,simpleProxyRules,callback);
	console.debug("function getSimpleProxySetting end");
}

//获取详细设置
function getAdvancedProxySetting(isEnable,callback){
	console.debug("function getAdvancedProxySetting start");
	bypass_list = getBypassList(callback);
    var http_proxy_address = document.getElementById("http_proxy_address").value;
	var http_port = Number(document.getElementById("http_port").value);
	var http_server_protocol = document.getElementById("http_server_protocol").value;

	var https_proxy_address = document.getElementById("https_proxy_address").value;
	var https_port = Number(document.getElementById("https_port").value);
	var https_server_protocol = document.getElementById("https_server_protocol").value;

	var ftp_proxy_address = document.getElementById("ftp_proxy_address").value;
	var ftp_port = Number(document.getElementById("ftp_port").value);
	var ftp_server_protocol = document.getElementById("ftp_server_protocol").value;

	var fallback_proxy_address = document.getElementById("fallback_proxy_address").value;
	var fallback_port = Number(document.getElementById("fallback_port").value);
	var fallback_server_protocol = document.getElementById("fallback_server_protocol").value;
	
	advancedProxyRules = {
	    proxyForHttp : {scheme:http_server_protocol,host:http_proxy_address,port:http_port},
	    proxyForHttps : {scheme:https_server_protocol,host:https_proxy_address,port:https_port},
		proxyForFtp : {scheme:ftp_server_protocol,host:ftp_proxy_address,port:ftp_port},
		fallbackProxy : {scheme:fallback_server_protocol,host:fallback_proxy_address,port:fallback_port},
		bypassList: bypass_list
	}
	fixedServersProxy(isEnable,advancedProxyRules,callback);
	console.debug("function getAdvancedProxySetting end");
}
